package oyl.selenium;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import oyl.selenium.config.AbstractDriver;
import oyl.selenium.config.translate.HttpUtils;
import oyl.selenium.config.MyWebDriver;
import oyl.selenium.config.translate.TranslateUtils;
import oyl.selenium.entity.Article;
import oyl.selenium.entity.Sinovinyl;
import oyl.selenium.entity.UserSettings;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by Nicky.Tang on 2021/9/18 1:41 下午
 * mvn compile assembly:single  -DskipTests
 * @since 02.12.10
 */
public class Start {


    public static void main(String[] args) throws Exception {
        try {
            checkVersion();
            //System.out.println("GetPropertyFilePath：》》》》" + getPropertyFilePath("chromedriver"));
            System.out.println("GetPropertyFilePath：》》》》" + getPropertyFilePath("chromedriver.exe"));
            //System.setProperty("webdriver.chrome.driver", "/Users/piangpiang/Documents/my-workspace/my-mayun/tjs.version.controller/src/main/resources/chromedriver");
            //System.setProperty("webdriver.chrome.driver","C:\\Workspace\\sinovinyl\\config\\chromedriver.exe");
            System.setProperty("webdriver.chrome.driver", getPropertyFilePath("chromedriver.exe"));

            //UserSettings userSettings = JSONObject.parseObject(readTxt("/Users/piangpiang/Documents/my-workspace/my-mayun/tjs.version.controller/src/main/resources/sinovinyl_settings.json5"), UserSettings.class);
            UserSettings userSettings = JSONObject.parseObject(readTxt(getPropertyFilePath("sinovinyl_settings.json5")), UserSettings.class);
            List<Sinovinyl> data = userSettings.getData();
            if (!"probation".equals(userSettings.getPlugin().getUserName()) || !"probation123".equals(userSettings.getPlugin().getUserPassword())) {
                System.out.println("插件用户名-密码不匹配，请联系开发人员，开发人员qq: 1264371179");
                System.out.println("插件用户名-密码不匹配，请联系开发人员，开发人员qq: 1264371179");
                System.out.println("插件用户名-密码不匹配，请联系开发人员，开发人员qq: 1264371179");
                System.out.println("即将退出，，，");
                Thread.sleep(60000);
                return;
            }
            if (CollectionUtils.isEmpty(data)) {
                throw new RuntimeException("请正确配置data属性-待发布的文章！");
            }

            ChromeOptions options = new ChromeOptions();
            options.setPageLoadStrategy(PageLoadStrategy.EAGER);
//        options.setExperimentalOption("debuggerAddress", "127.0.0.1:22632");
            WebDriver driver = new ChromeDriver(options);
//        WebDriver driver = new FirefoxDriver();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);//默认寻找元素的超时时间
            driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);//默认寻找元素的超时时间
            driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);//默认寻找元素的超时时间

            writeArticle(userSettings, data, driver);

            System.out.println("所有任务处理完成，即将退出，，，");
            Thread.sleep(9999999);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("部分任务处理异常，即将退出，，，");
            Thread.sleep(9999999);
        }

    }

    public static void addCookie(String value, WebDriver driver) {
        value = value.replace(" ", "");
        if (value.contains(";")) {
            String[] values = value.split(";");
            for (String val : values) {
                String[] vals = val.split("=");
                driver.manage().addCookie(new Cookie(vals[0], vals[1]));
            }
        } else {
            String[] values = value.split("=");
            driver.manage().addCookie(new Cookie(values[0], values[1]));
        }
    }
    public static String readTxt(String filename) {
        File file = new File(filename);
        StringBuilder sb = new StringBuilder();
        try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) {
            if (file.isFile() && file.exists()) {
                BufferedReader bufferedReader = new BufferedReader(read);
                String readLine = null;
                while ((readLine = bufferedReader.readLine()) != null) {
                    sb.append(readLine).append("\n");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("xml数据读取错误");
        }
        return sb.toString();
    }

    public static String getPropertyFilePath(String propertyFile) throws IOException {
        String jarWholePath = Start.class.getProtectionDomain().getCodeSource().getLocation().getFile();
        jarWholePath = java.net.URLDecoder.decode(jarWholePath, "UTF-8");
        String jarPath = new File(jarWholePath).getParentFile().getAbsolutePath() + "\\config\\" + propertyFile;
//        String jarPath = new File(jarWholePath).getParentFile().getAbsolutePath() + "\\classes\\" + propertyFile;
        return jarPath;
    }

    private static void checkVersion() throws InterruptedException {
        String versions = HttpUtils.doGet("https://gitee.com/tangjingshan/tjs.version.controller");
        if (StringUtils.isEmpty(versions) || versions.indexOf("404 Not Found") != -1) {
            System.out.println("请联系开发人员注册账号！开发人员qq: 1264371179");
            System.out.println("请联系开发人员注册账号！开发人员qq: 1264371179");
            System.out.println("请联系开发人员注册账号！开发人员qq: 1264371179");
            Thread.sleep(999999);
            throw new RuntimeException("请联系开发人员注册账号！开发人员qq: 1264371179");
        }
    }

    private static void writeArticle(UserSettings userSettings, List<Sinovinyl> data, WebDriver driver) {
        Sinovinyl sinovinylFirst = data.stream().filter(item -> Boolean.TRUE.equals(item.getIffirst())).findAny().orElse(null);
        List<Article> articleFirst = sinovinylFirst != null && sinovinylFirst.getArticle() != null ? sinovinylFirst.getArticle() : new ArrayList<>();
        List<Article> articleAll = new ArrayList<>();
        resetArticle(data, articleFirst, articleAll);
        //翻译所有的
        //TranslateUtils.translate(articleAll);

        for (Sinovinyl sinovinyl : data) {
            try {
                System.out.println(">>>>>>开始处理：" + sinovinyl.getLanguageCN() + "_" + sinovinyl.getWeburl());
                if (!Boolean.TRUE.equals(sinovinyl.getIfopenpublish())) {
                    System.out.println(">>>>>>完成处理：" + sinovinyl.getLanguageCN() + "_" + sinovinyl.getWeburl() + "\n");
                    continue;
                }
                MyWebDriver myWebDriver = new MyWebDriver(driver, sinovinyl.getWeburl(), userSettings.getSinovinylName(), userSettings.getSinovinylPassword());
                myWebDriver.openLoginPage();
                addCookie(sinovinyl.getSinovinylCookie(), driver);
                Thread.sleep(600);
                driver.navigate().refresh();
                Thread.sleep(1000);
                try {
                    if(driver.findElement(By.xpath(".//*[@href='post-new.php']"))==null){
                        System.out.println("cookie失效，重新登录，，，，");
                        myWebDriver.login(sinovinyl);//登陆
                    }
                }catch (Exception ex){
                    //ex.printStackTrace();
                    System.out.println("cookie失效，重新登录，，，，");
                    myWebDriver.login(sinovinyl);//登陆
                }

                List<Article> article = sinovinyl.getArticle();
                int j = 0;
                for (Article articleItem : article) {
                    j++;
                    TranslateUtils.translate(articleItem);
                    myWebDriver.writeArticle(userSettings, sinovinyl, articleItem, j == article.size());//写文章
                }
                System.out.println(">>>>>>完成处理：" + sinovinyl.getLanguageCN() + "_" + sinovinyl.getWeburl() + "\n");
            } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println(">>>>>>失败处理：" + sinovinyl.getLanguageCN() + "_" + sinovinyl.getWeburl() + "\n");
            }
        }
    }

    private static void resetArticle(List<Sinovinyl> data, List<Article> articleFirst, List<Article> articleAll) {
        for (Sinovinyl sinovinyl : data) {
            List<Article> article = sinovinyl.getArticle() != null ? sinovinyl.getArticle() : new ArrayList<>();
            if (CollectionUtils.isEmpty(article) && CollectionUtils.isEmpty(articleFirst)) {
                System.out.println(sinovinyl.getLanguage() + " 没有待发布的文章！");
                continue;
            }
            if (!Boolean.TRUE.equals(sinovinyl.getIfopenpublish())) {
                System.out.println(sinovinyl.getLanguage() + " 没有待发布的文章！");
                continue;
            }
            if (!Boolean.TRUE.equals(sinovinyl.getIffirst())) {
                List<Article> articleFirstCopy = JSON.parseObject(JSON.toJSONString(articleFirst), new TypeReference<List<Article>>() {
                });
                article.addAll(articleFirstCopy);
            }
            for (Article articleItem : article) {
                articleItem.setId(UUID.randomUUID().toString());//重置id
                articleItem.setLanguageCN(sinovinyl.getLanguageCN());
                articleItem.setLanguage(sinovinyl.getLanguage());
            }
            sinovinyl.setArticle(article);
            articleAll.addAll(sinovinyl.getArticle());
        }
    }


}
